import 'package:carousel_slider/carousel_slider.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_xxyk/constant/api.dart';
import 'package:flutter_xxyk/constant/routes.dart';
import 'package:flutter_xxyk/model/shop_decoration.dart';
import 'package:get_it/get_it.dart';
import 'package:skeletons/skeletons.dart';

extension NullExt<T> on T {
  R run<R>(R Function(T it) block) => block(this);
}

class IndexPage extends StatefulWidget {
  const IndexPage({Key? key}) : super(key: key);

  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  final Dio dio = GetIt.I<Dio>();

  ShopDecoration? shopDecoration;

  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    getShopDecoration();
  }

  Future<void> getShopDecoration() async {
    _isLoading = true;
    final res = await dio.get("/h5/shop/decorate/fetch", queryParameters: {'shop_id': ApiConstant.SHOP_ID});
    final data = ShopDecoration.fromJson(res.data["data"]);
    setState(() {
      shopDecoration = data;
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
        child: RefreshIndicator(
          onRefresh: getShopDecoration,
          child: SingleChildScrollView(
            physics: AlwaysScrollableScrollPhysics(),
            child: Skeleton(
              isLoading: _isLoading,
              skeleton: _skeleton(),
              child: Column(
                children: [
                  _buildSearchBar(),
                  _buildSlider(),
                  _buildNavigation(),
                  _buildColumn(),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _skeleton() {
    return SkeletonItem(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          children: [
            SizedBox(
              height: 20,
            ),
            SkeletonLine(
              style: SkeletonLineStyle(height: 40, width: MediaQuery.of(context).size.width - 40, borderRadius: BorderRadius.circular(8)),
            ),
            SizedBox(
              height: 50,
            ),
            SkeletonAvatar(
              style: SkeletonAvatarStyle(
                width: double.infinity,
                height: MediaQuery.of(context).size.height / 8,
              ),
            ),
            SizedBox(
              height: 50,
            ),
            SkeletonParagraph(
              style: SkeletonParagraphStyle(
                  lines: 3,
                  spacing: 16,
                  lineStyle: SkeletonLineStyle(
                    randomLength: true,
                    height: 10,
                    borderRadius: BorderRadius.circular(8),
                    minLength: MediaQuery.of(context).size.width / 2,
                    maxLength: MediaQuery.of(context).size.width,
                  )),
            ),
            SizedBox(
              height: 50,
            ),
            SkeletonAvatar(
              style: SkeletonAvatarStyle(
                width: double.infinity,
                height: MediaQuery.of(context).size.height / 4,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSearchBar() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(10),
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(10),
          child: Container(
            color: Color(0xfff6f6f6),
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
            child: Row(
              children: [
                Image.asset("assets/images/search.png"),
                Padding(
                  padding: EdgeInsets.only(left: 10),
                  child: Text(
                    "请输入搜索关键词",
                    style: TextStyle(
                      color: Color(0xff999999),
                      fontSize: 17,
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildSlider() {
    var bannerL = shopDecoration?.configData?.components?.where((element) => element.name == 'banner');
    if (bannerL != null && bannerL.isNotEmpty) {
      final bannerC = bannerL.first;
      var bannerInfo = bannerC.informationConfig;
      final items = bannerInfo?.list
          ?.map((e) => Image.network(
                e['img'],
                fit: BoxFit.fill,
                width: double.infinity,
              ))
          .toList();
      return Padding(
        padding: EdgeInsets.symmetric(horizontal: 20),
        child: CarouselSlider(
            items: items,
            options: CarouselOptions(
              viewportFraction: 1.0,
              enlargeCenterPage: false,
            )),
      );
    }
    return SizedBox.shrink();
  }

  Widget _buildNavigation() {
    var navL = shopDecoration?.configData?.components?.where((element) => element.name == 'navigation');
    if (navL != null && navL.isNotEmpty) {
      final navC = navL.first;
      var navInfo = navC.informationConfig;
      final items = navInfo?.list
          ?.map((e) => Expanded(
                child: Column(
                  children: [
                    ConstrainedBox(
                      constraints: BoxConstraints(minHeight: 70, minWidth: 70),
                      child: Image.network(
                        e['img'],
                        fit: BoxFit.fill,
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.symmetric(vertical: 5),
                      child: Text(e['name']),
                    ),
                  ],
                ),
              ))
          .toList();

      return Padding(
        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: items!,
        ),
      );
    }
    return SizedBox.shrink();
  }

  Widget _buildColumn() {
    var columnL = shopDecoration?.configData?.components?.where((element) => element.name == 'column');
    if (columnL != null && columnL.isNotEmpty) {
      final columnC = columnL.first;
      var columnInfo = columnC.informationConfig;
      final items = columnInfo?.list?.map(
        (e) {
          final d = e['_data'];
          return InkWell(
            onTap: () {
              Navigator.of(context).pushNamed(AppRoutes.COLUMN_DETAIL, arguments: d['productId']);
            },
            child: Column(
              children: [
                ConstrainedBox(
                  constraints: BoxConstraints(
                    minWidth: 340,
                    minHeight: 180,
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(4),
                    child: Image.network(
                      d['imgUrl'],
                    ),
                  ),
                ),
                Container(
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(vertical: 5),
                  child: Text(
                    d['title'],
                    textAlign: TextAlign.left,
                    style: TextStyle(fontSize: 16),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      decoration: BoxDecoration(color: Color(0xffffeee7), borderRadius: BorderRadius.circular(1)),
                      padding: EdgeInsets.symmetric(vertical: 3, horizontal: 4),
                      child: d['payType'] == 0
                          ? Text(
                              '免费',
                              style: TextStyle(color: Color(0xffff6825)),
                            )
                          : Text(
                              '收费',
                              style: TextStyle(color: Color(0xffff6825)),
                            ),
                    ),
                    Text(
                      "${d['userCnt']}人加入",
                      style: TextStyle(
                        fontSize: 12,
                        color: Color(0xff9d9fa7),
                      ),
                    )
                  ],
                ),
                SizedBox(
                  height: 20,
                ),
              ],
            ),
          );
        },
      ).toList();

      return Padding(
        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Padding(
              padding: EdgeInsets.only(bottom: 5),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "专栏",
                    style: TextStyle(
                      fontSize: 22,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text(
                    "查看更多",
                    style: TextStyle(
                      fontSize: 14,
                      color: Color(0xff9d9fa7),
                    ),
                  )
                ],
              ),
            ),
            ...items!,
          ],
        ),
      );
    }
    return SizedBox.shrink();
  }
}
